package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.PageDto;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.enums.HttpEnum;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.utils.LoginThreadLocal;
import com.itheima.reggie.utils.PageUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 菜品管理(Dish)表服务实现类
 *
 * @author shenjiaqi
 * @since 2024-02-02 00:02:51
 */
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Resource
    private CategoryService categoryService;
    @Resource
    private DishFlavorService dishFlavorService;

    /**
     * 菜品信息分页查询
     *
     * @param dto
     * @return
     */
    @Override
    public R pageList(PageDto dto) {
        //参数校验
        if (null == dto) {
            return R.error(HttpEnum.PARAMETER_NULL.getMsg());
        }
        PageUtils.setPage(dto);
//        PageHelper.startPage(dto.getPage(), dto.getPageSize());

        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = Wrappers.<Dish>lambdaQuery()
                .like(StringUtils.isNotBlank(dto.getName()), Dish::getName, dto.getName())
                //  .eq(Dish::getStatus,)
                .orderByAsc(Dish::getSort)
                .orderByDesc(Dish::getUpdateTime);
        Page<Dish> dishPage = page(new Page<>(dto.getPage(), dto.getPageSize()), dishLambdaQueryWrapper
        );
        if (CollectionUtils.isEmpty(dishPage.getRecords())) {
            return R.success(new Page<DishDto>());
        }
        Page<DishDto> dishDtoPage = new Page<>();
        BeanUtils.copyProperties(dishPage, dishDtoPage, "records");

        List<Dish> dishList = dishPage.getRecords();
        if (CollectionUtils.isEmpty(dishList)) {
            return R.success(null);
        }
        // 分类id集合
        List<Long> categoryIds = dishList.stream().map(Dish::getCategoryId).collect(Collectors.toList());
        // 分类集合
        List<Category> categoryList = categoryService.list(Wrappers.<Category>lambdaQuery()
                .in(Category::getId, categoryIds));

        // id:name map(Category)
        Map<Long, String> categoryMap = categoryList.stream().collect(Collectors.toMap(Category::getId, Category::getName));
        // 封装
        List<DishDto> dishDtoList = dishList.stream().map(dish -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish, dishDto);
            // 根据id拿map中的name
            dishDto.setCategoryName(categoryMap.get(dish.getCategoryId()));
            return dishDto;
        }).collect(Collectors.toList());

        dishDtoPage.setRecords(dishDtoList);

        return R.success(dishDtoPage);
        // PageInfo<Dish> dishDtoPageInfo = new PageInfo<>(dishDtoList);
        // return R.success(new HashMap<String, Object>() {{
        //     put("total", dishDtoPageInfo.getTotal());
        //     put("records", dishDtoPageInfo.getList());
        // }});
    }

    /**
     * 菜品新增
     *
     * @param dto
     * @return
     */
    @Transactional// 多表操作 添加事务
    @Override
    public R add(DishDto dto) {
        // 参数校验
        if (null == dto) {
            return R.error(HttpEnum.PARAMETER_ERROR.getMsg());
        }
        // 菜品封装
        Dish dish = new Dish();
        BeanUtils.copyProperties(dto, dish);
        dish.setCreateUser(LoginThreadLocal.getCurrent());
        dish.setUpdateUser(LoginThreadLocal.getCurrent());
        dish.setCreateTime(new Date());
        dish.setUpdateTime(new Date());
        // 保存
        save(dish);
        // 口味封装
        List<DishFlavor> flavors = dto.getFlavors();
        // 不为空
        if (!CollectionUtils.isEmpty(flavors)) {
            List<DishFlavor> dishFlavorList = flavors.stream().map(flavor -> {
                DishFlavor dishFlavor = new DishFlavor();
                dishFlavor.setDishId(dish.getId());
                dishFlavor.setName(flavor.getName());
                dishFlavor.setValue(flavor.getValue());
                dishFlavor.setCreateUser(LoginThreadLocal.getCurrent());
                dishFlavor.setUpdateUser(LoginThreadLocal.getCurrent());
                dishFlavor.setCreateTime(new Date());
                dishFlavor.setUpdateTime(new Date());
                // 0否1真
                dishFlavor.setIsDeleted(0);
                return dishFlavor;
            }).collect(Collectors.toList());
            // 批量插入
            dishFlavorService.saveBatch(dishFlavorList);
        }
        // 返回响应
        return R.success("菜品新增成功!!");
    }

    /**
     * 单菜品详情
     *
     * @param id
     * @return
     */
    @Override
    public R getDetailsById(Long id) {
        if (null == id) {
            return R.error(HttpEnum.PARAMETER_NULL.getMsg());
        }
        Dish byId = getById(id);
        if (null == byId || byId.getCategoryId() == null) {
            return R.error("该菜品信息有误");
        }
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(byId, dishDto);
        // 分类名称
        String categoryName = categoryService.getById(byId.getCategoryId()).getName();
        dishDto.setCategoryName(categoryName);
        // 口味详情
        List<DishFlavor> dishFlavors = dishFlavorService.list(Wrappers.<DishFlavor>lambdaQuery()
                .eq(DishFlavor::getDishId, byId.getId()));
        // 口味不为空
        if (!CollectionUtils.isEmpty(dishFlavors)) {
            dishDto.setFlavors(dishFlavors);
        }
        return R.success(dishDto);
    }

    /**
     * 单个菜品修改
     *
     * @param dto
     * @return
     */
    @Transactional
    @Override
    public R updateByDetail(DishDto dto) {
        // 参数校验
        if (dto == null || null == dto.getId()) {
            return R.error(HttpEnum.PARAMETER_NULL.getMsg());
        }
        // 拷贝封装
        Dish dish = new Dish();
        BeanUtils.copyProperties(dto, dish);
        // 修改保存
        dish.setUpdateTime(new Date());
        dish.setUpdateUser(LoginThreadLocal.getCurrent());
        updateById(dish);
        // 口味
        if (!CollectionUtils.isEmpty(dto.getFlavors())) {
            List<DishFlavor> dishFlavorList = dto.getFlavors().stream()
                    // 过滤空对象|name为空的对象
                    .filter(flavor -> null != flavor && Objects.nonNull(flavor.getName()))
                    .map(flavor -> {
                        flavor.setDishId(dto.getId());
                        flavor.setIsDeleted(0);
                        flavor.setCreateTime(new Date());
                        flavor.setCreateUser(LoginThreadLocal.getCurrent());
                        flavor.setUpdateTime(new Date());
                        flavor.setUpdateUser(LoginThreadLocal.getCurrent());
                        return flavor;
                    })
                    .collect(Collectors.toList());
            // 先删后增
            boolean remove = dishFlavorService.remove(Wrappers.<DishFlavor>lambdaQuery()
                    .eq(DishFlavor::getDishId, dto.getId()));
            if (!remove) {
                return R.error("菜品修改口味数据删除失败!");
            }
            // 批量插入
            dishFlavorService.saveBatch(dishFlavorList);
        }
        return R.success("菜品修改成功");
    }

    /**
     * 批量上下架
     *
     * @param status
     * @param ids
     * @return
     */
    @Override
    public R updateStatus(String status, List<String> ids) {
        if (StringUtils.isBlank(status) || CollectionUtils.isEmpty(ids) || ids.size() == 0) {
            return R.error(HttpEnum.PARAMETER_NULL.getMsg());
        }
        if (!(StringUtils.equals("0", status) || StringUtils.equals("1", status))) {
            return R.error(HttpEnum.PARAMETER_ERROR.getMsg());
        }
        List<Dish> dishList = list(Wrappers.<Dish>lambdaQuery()
                .in(Dish::getId, ids));
        // List<Dish> newDishes = dishList.stream().map(dish -> {
        //             dish.setStatus(Integer.parseInt(status));
        //             dish.setUpdateUser(LoginThreadLocal.getCurrent());
        //             dish.setUpdateTime(new Date());
        //             return dish;
        //         })
        //         .collect(Collectors.toList());

        dishList.stream().forEach(dish -> {
            dish.setStatus(Integer.parseInt(status));
            dish.setUpdateUser(LoginThreadLocal.getCurrent());
            dish.setUpdateTime(new Date());
        });
        // 批量更新 默认根据集合中对象Id进行更新
        updateBatchById(dishList);
        return R.success(StringUtils.equals(status, "0") ? "批量停售成功" : "批量起售成功");
    }
}

